//
//  ShopViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/6/20.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "ShopViewController.h"
#import "ShopTableViewCell.h"
#import "MapLocationViewController.h"
#import "AddShopViewController.h"
#import "NewAddShopViewController.h"
#import "SRActionSheet.h"
#import "BorderHelper.h"
#import "ShopChooseItemsViewController.h"
#define kCellName @"ShopTableViewCell"

#import "PowerBelongViewController.h"

#define kPageSize @"20"

@interface ShopViewController ()<SRActionSheetDelegate,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating,ShopChooseItemsViewControllerDelegate>
{
    BOOL _isHas;
    NSString *_type;
    NSInteger _count;
    NSInteger _pageIndex;
    NSString *_shopChooseType;
}
@property (nonatomic,retain) UISearchController *searchController;


@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableArray *searchListArry;

@end

@implementation ShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _isHas = YES;
    [self UISetting];
    [self creatSearchBar];
    
    //从首页带入值，如果不带，默认选中已铺设，若传入则根据值判断；0->已铺设 ； 1->待铺设
    if (_typeValue.integerValue == 1) {
        [self PuSheButtonClick:_button2];
    }else{
        [self PuSheButtonClick:_button1];
    }
    
//    [self setSubView];

    
    [self chooseListOrMap:_segmentControl];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    

    if (_count > 0) {
        [self loadListDataByStatus:_type];
    }
    _count ++;

    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMap" object:nil];
}

- (void)UISetting{
    _dataArray = [NSMutableArray array];
    _searchListArry = [NSMutableArray array];
    
    _topView.alpha = 0.8;
    _topView.layer.masksToBounds = YES;
    _topView.layer.cornerRadius = 5.f;
    
    _topView.layer.borderColor = [kColorFrom0x(0xf5f5f5) CGColor];
    _topView.layer.borderWidth = 1.f;
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [_tableView addGestureRecognizer:tableViewGesture];

    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageIndex = 0;
        [self loadListDataByStatus:_type];
        
        [_tableView.mj_header endRefreshing];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _pageIndex ++;
        [self loadListDataByStatus:_type];
        [_tableView.mj_footer endRefreshing];
    }];
}

- (void)commentTableViewTouchInSide{
    [_searchController.searchBar resignFirstResponder];
}

- (void)creatSearchBar{
    //创建UISearchController
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //设置代理
    self.searchController.delegate= self;
    self.searchController.searchResultsUpdater = self;
    
    //包着搜索框外层的颜色
    self.searchController.searchBar.barTintColor = kColorFrom0x(0xf5f5f5);
    
    [self.searchController.searchBar setBackgroundImage:[UIImage new]];
    [self.searchController.searchBar setBackgroundColor:kColorFrom0x(0xf5f5f5)];

    UITextField *textField = [self.searchController.searchBar valueForKey:@"_searchField"];
    textField.layer.masksToBounds = YES;
    textField.layer.borderWidth = 0.5;
    textField.layer.borderColor = [kColorFrom0x(0xdedee0) CGColor];
    textField.layer.cornerRadius = kButtonCornerRadius ;
    [BorderHelper setOnlyUnderLineColor:kColorFrom0x(0xeeeeee) view:self.searchController.searchBar];
    
    
    self.searchController.searchBar.tintColor = kGreenColor;
    



    //提醒字眼
    self.searchController.searchBar.placeholder= @"请输入关键字搜索";
    
    //搜索时，背景变暗色
        self.searchController.dimsBackgroundDuringPresentation = NO;
    //搜索时，背景变模糊
    //    self.searchController.obscuresBackgroundDuringPresentation = NO;
    
    //点击搜索的时候,是否隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    
    //位置
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    
    // 添加 searchbar 到 headerview
    self.tableView.tableHeaderView = self.searchController.searchBar;

    self.definesPresentationContext=YES;

    
}

- (void)setSubView{
    UIStoryboard *storyboard = kMainStroyboard;
    MapLocationViewController *map = [storyboard instantiateViewControllerWithIdentifier:@"MapLocationViewController"];
    [self addChildViewController:map];
    [_mapBackgroundView addSubview:map.view];
}

#pragma mark - 网络请求

- (void)loadListDataByStatus:(NSString *)status{
    [self.hub hideAnimated:YES];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    
    NSString *shopChooseType ;
    if (_shopChooseType.integerValue == 103) {
        shopChooseType = @"4";
    }else if (_shopChooseType.integerValue == 102){//wifi
        shopChooseType = @"1";
    }else{//mima
        shopChooseType = nil;
    }
    
    
    NSString *pageIndexString = [NSString stringWithFormat:@"%ld",_pageIndex];
    [[AFClient shareInstance] getShopListByEid:kUserId page_size:kPageSize page_index:pageIndexString status:status store_type:shopChooseType progressBlock:nil success:^(id responseBody) {

        [self.hub hideAnimated:YES];
        

        
        if ([responseBody[@"code"] integerValue] == 200) {
            if (_pageIndex == 0) {
                [_dataArray removeAllObjects];
            }
            for (NSDictionary *dic in responseBody[@"data"]) {
                ShopModel *model = [[ShopModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_dataArray addObject:model];
            }
        }else{
            kAlert(responseBody[@"message"]);
        }
        
        [self creatImageBackView:_dataArray];
        
        [_tableView reloadData];
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)shaixuanHidden:(BOOL)isHidden{
    _buttonShaixuan.hidden = isHidden;
    _imageViewShaixuan.hidden= isHidden;
}
#pragma mark - 点击事件

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)shaiXuanButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
    ShopChooseItemsViewController *chooseItemVC = [storyboard instantiateViewControllerWithIdentifier:@"ShopChooseItemsViewController"];
    if ([BGFunctionHelper isNULLOfString:_shopChooseType]) {
        _shopChooseType = @"101";
    }
    chooseItemVC.typeValue = _shopChooseType;
    chooseItemVC.delegate = self;
    chooseItemVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:chooseItemVC animated:YES completion:nil];
}


//添加门店
- (IBAction)addButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
    NewAddShopViewController *addShopVC = [storyboard instantiateViewControllerWithIdentifier:@"NewAddShopViewController"];
    addShopVC.jumpType = @"2";

    [self.navigationController pushViewController:addShopVC animated:YES];
}


//选择列表或是地图显示
- (IBAction)chooseListOrMap:(UISegmentedControl *)sender {
    _pageIndex = 0;
    if (sender.selectedSegmentIndex == 1) {

            [self shaixuanHidden:YES];

        _shopChooseType = @"102";
        _type = @"1";

        _viewYiPushe.backgroundColor = kGreenColor;
        _viewDaiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
    }else if (sender.selectedSegmentIndex == 2){
        [self shaixuanHidden:YES];
        
        _shopChooseType = @"103";
        _type = @"1";

        _viewYiPushe.backgroundColor = kGreenColor;
        _viewDaiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
    }
    else{
        [self shaixuanHidden:YES];
        _type = @"0";

        _shopChooseType = @"101";

    }
    [self loadListDataByStatus:_type];
}


/**
 tag = 200 -> yipushe
 tag = 201 -> daipushe
 */
- (IBAction)PuSheButtonClick:(UIButton *)sender {
    _pageIndex = 0;
    if (sender.tag == 200) {//已铺设
        _viewYiPushe.backgroundColor = kGreenColor;
        _viewDaiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
        _type = @"1";
        _isHas = YES;
//        [self shaixuanHidden:NO];
    }else{//待铺设
        _viewYiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
        
        _viewDaiPushe.backgroundColor = kGreenColor;
        _type = @"0";
        _isHas = NO;
        _shopChooseType = @"101";
        
        _segmentControl.selectedSegmentIndex = 0;
//        [self shaixuanHidden:YES];
    }
    [self loadListDataByStatus:_type];

}



#pragma mark - tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_searchController.active) {
        return _searchListArry.count;
    }
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopTableViewCell *cell = (ShopTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCellName];

    if (self.searchController.active) {
        ShopModel *model = _searchListArry[indexPath.row];
        
        [cell showDataWithModel:model];
    }else{
        ShopModel *model = _dataArray[indexPath.row];
        
        [cell showDataWithModel:model];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopTableViewCell *cell = (ShopTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    return [cell height];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.searchController.active) {
        ShopModel *model = _searchListArry[indexPath.row];
        
        SRActionSheet *actionSheet ;
        if (_isHas) {
            actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:nil
                                                         cancelTitle:@"取消"
                                                    destructiveTitle:nil
                                                         otherTitles:@[@"所属充电宝", @"编辑门店", @"删除"]
                                                         otherImages:nil
                                                   selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
                                                       NSLog(@"%zd", index);
                                                       if (index == 0) {
                                                           [self powerBelongFunByShopId:model];
                                                       }else if (index == 1){
                                                           [self editShopInfoFun:model];
                                                       }else{
                                                           [self deleteFunByShopId:model.id];
                                                       }
                                                   }];
        }else{
            actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:nil
                                                         cancelTitle:@"取消"
                                                    destructiveTitle:nil
                                                         otherTitles:@[@"所属充电宝", @"编辑门店", @"已铺设", @"删除"]
                                                         otherImages:nil
                                                   selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
                                                       NSLog(@"%zd", index);
                                                       if (index == 0) {
                                                           [self powerBelongFunByShopId:model];
                                                       }else if (index == 1){
                                                           [self editShopInfoFun:model];
                                                       }else if (index == 2){
                                                           [self hasSettedFunByShopId:model.id];
                                                       }else{
                                                           [self deleteFunByShopId:model.id];
                                                       }
                                                   }];
        }
        
        [actionSheet show];
    }else{
        ShopModel *model = _dataArray[indexPath.row];
        
        SRActionSheet *actionSheet ;
        if (_isHas) {
            actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:nil
                                                         cancelTitle:@"取消"
                                                    destructiveTitle:nil
                                                         otherTitles:@[@"所属充电宝", @"编辑门店", @"待铺设", @"删除"]
                                                         otherImages:nil
                                                   selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
                                                       NSLog(@"%zd", index);
                                                       if (index == 0) {
                                                           [self powerBelongFunByShopId:model];
                                                       }else if (index == 1){
                                                           [self editShopInfoFun:model];
                                                       }else if (index == 2){
                                                           if (model.all_num.integerValue == 0) {
                                                               [self waitingSettedFunByShopId:model.id];
                                                           }else{
                                                               UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"该店铺下还有充电宝未撤回，无法设置" message:nil preferredStyle:UIAlertControllerStyleAlert];
                                                               UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                                                               }];
                                                               [alert addAction:action];
                                                               [self presentViewController:alert animated:YES completion:nil];
                                                           }
                                                       }else{
                                                           [self deleteFunByShopId:model.id];
                                                       }
                                                   }];
        }else{
            actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:nil
                                                         cancelTitle:@"取消"
                                                    destructiveTitle:nil
                                                         otherTitles:@[@"所属充电宝", @"编辑门店", @"已铺设", @"删除"]
                                                         otherImages:nil
                                                   selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
                                                       NSLog(@"%zd", index);
                                                       if (index == 0) {
                                                           [self powerBelongFunByShopId:model];
                                                       }else if (index == 1){
                                                           [self editShopInfoFun:model];
                                                       }else if (index == 2){
                                                           [self hasSettedFunByShopId:model.id];
                                                       }else{
                                                           [self deleteFunByShopId:model.id];
                                                       }
                                                   }];
        }
        
        [actionSheet show];
    }
    
}

#pragma mark - SRActionSheetDelegate

- (void)actionSheet:(SRActionSheet *)actionSheet didSelectSheet:(NSInteger)index {
    
        UIStoryboard *storyoboard = kMainStroyboard;
        PowerBelongViewController *powerBelongVC = [storyoboard instantiateViewControllerWithIdentifier:@"PowerBelongViewController"];
        [self.navigationController pushViewController:powerBelongVC animated:YES];
    
}

#pragma mark - 筛选代理

- (void)chooseItemsInShopVCWithNum:(NSString *)numString{
    _shopChooseType = numString;
    _pageIndex = 0;
    [self loadListDataByStatus:_type];
}

#pragma mark - actionSheet功能

#pragma mark - 所属充电宝
- (void)powerBelongFunByShopId:(ShopModel *)model{
    UIStoryboard *storyoboard = kMainStroyboard;
    PowerBelongViewController *powerBelongVC = [storyoboard instantiateViewControllerWithIdentifier:@"PowerBelongViewController"];
    powerBelongVC.model = model;
    [self.navigationController pushViewController:powerBelongVC animated:YES];
}

#pragma mark - 编辑门店

- (void)editShopInfoFun:(ShopModel *)model{
    UIStoryboard *storyboard = kMainStroyboard;
    NewAddShopViewController *addShopVC = [storyboard instantiateViewControllerWithIdentifier:@"NewAddShopViewController"];
    addShopVC.jumpType = @"1";
    addShopVC.model = model;
    [self.navigationController pushViewController:addShopVC animated:YES];
}

#pragma mark - 已铺设

- (void)hasSettedFunByShopId:(NSString *)shopId{
//    kAlert(@"已铺设");
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] setToHasUsedById:shopId eid:kUserId progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"铺设成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self loadListDataByStatus:_type];
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)waitingSettedFunByShopId:(NSString *)shopId{
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] waitToHasUsedById:shopId eid:kUserId progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"该店铺已变更为待铺设" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self loadListDataByStatus:_type];
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

#pragma mark - 删除
- (void)deleteFunByShopId:(NSString *)shopId{
//    kAlert(@"删除");
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认要删除吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        // Set the label text.
        self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
        [[AFClient shareInstance] deleteShopById:shopId eid:kUserId progressBlock:nil success:^(id responseBody) {
            [self.hub hideAnimated:YES];

            if ([responseBody[@"code"] integerValue] == 200) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"删除成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self loadListDataByStatus:_type];
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                kAlert(responseBody[@"message"]);
            }
        } failure:^(NSError *error) {
            [self.hub hideAnimated:YES];
        }];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action2];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark - searchBarDelegate

//谓词搜索过滤
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSLog(@"updateSearchResultsForSearchController");
    NSString *searchString = [self.searchController.searchBar text];
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    if (self.searchListArry .count > 0) {
        [self.searchListArry removeAllObjects];
    }
    
    NSMutableArray *nameArray = [NSMutableArray array];
    NSMutableArray *idsArray = [NSMutableArray array];
    for (ShopModel *model in _dataArray) {
        [nameArray addObject:model.name];
        [nameArray addObject:[NSString stringWithFormat:@"%@%@",model.area_name,model.specific_address]];
        [nameArray addObject:model.contact];
    }
    
    //过滤数据
    
    NSLog(@"nameArray = %@",nameArray);
    NSArray *searchedArray = [NSArray array];
    
    searchedArray = [NSArray arrayWithArray:[nameArray filteredArrayUsingPredicate:preicate]];
    
    for (unsigned i = 0; i < [searchedArray count]; i++){
        for (ShopModel *model in _dataArray) {
            if ([[searchedArray objectAtIndex:i] isEqualToString:model.name]) {
                if ([_searchListArry containsObject:model] == NO){
                    [_searchListArry addObject:model];
                }
            }else if ([[searchedArray objectAtIndex:i] isEqualToString:[NSString stringWithFormat:@"%@%@",model.area_name,model.specific_address]]){
                if ([_searchListArry containsObject:model] == NO){
                    [_searchListArry addObject:model];
                }
            }else if ([[searchedArray objectAtIndex:i] isEqualToString:model.contact]){
                if ([_searchListArry containsObject:model] == NO){
                    [_searchListArry addObject:model];
                }
            }
        }
    }
    
    [self creatImageBackView:_searchListArry];

    [_tableView reloadData];
}



#pragma mark - UISearchControllerDelegate代理
//测试UISearchController的执行过程

- (void)willPresentSearchController:(UISearchController *)searchController
{
    NSLog(@"willPresentSearchController");
}

- (void)didPresentSearchController:(UISearchController *)searchController
{
    NSLog(@"didPresentSearchController");
    
    //    [self.view addSubview:self.searchController.searchBar];
}

- (void)willDismissSearchController:(UISearchController *)searchController
{
    NSLog(@"willDismissSearchController");

}

- (void)didDismissSearchController:(UISearchController *)searchController
{
    NSLog(@"didDismissSearchController");
    [self creatImageBackView:_dataArray];
}

- (void)presentSearchController:(UISearchController *)searchController
{
    NSLog(@"presentSearchController");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
